package com.lzy.algorithm;

public class 链表相交 {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(7);
        ListNode l2 = new ListNode(6);
        ListNode l3 = new ListNode(100);
        ListNode l4 = new ListNode(-1);
        ListNode l5 = new ListNode(1);
        ListNode l6 = new ListNode(2);

        l1.next = l2;
        l2.next = l3;

        l6.next = l5;
        l5.next = l4;
        l4.next = l3;

        ListNode result = getIntersectionNode(l1, l6);
        System.out.println(result.val);
    }


    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode node1 = headA;
        ListNode node2 = headB;
        // 如果没有相交，那node1和node2都会走完两个链表，走完后是null
        while (node1 != node2) {
            if (node1 == null) {
                node1 = headB;
            } else {
                node1 = node1.next;
            }

            if (node2 == null) {
                node2 = headA;
            } else {
                node2 = node2.next;
            }
        }
        return node1;
    }
}
